#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/12/22 14:55
# @Author : 闫峰
# @File    : ceshi5.py
from concurrent.futures import ThreadPoolExecutor,as_completed


class MyThreadPool:
    """
    最新的多线程类 MyThreadPool
    """
    def __init__(self, max_workers):
        self.executor = ThreadPoolExecutor(max_workers=max_workers)

    def submit(self, func, *args, **kwargs):
        future = self.executor.submit(func, *args, **kwargs)

        future.args = args
        future.kwargs = kwargs
        return future

    def map(self, func, *iterables, timeout=None, chunksize=1):
        return self.executor.map(func, *iterables, timeout=timeout, chunksize=chunksize)

    def shutdown(self, wait=True):
        self.executor.shutdown(wait=wait)

    def get_result(self, future):
        try:
            result = future.result()
        except Exception as e:
            result = e
        args = future.args
        kwargs = future.kwargs
        return args, kwargs, result

    def multithreaded(self,func, task_list):
        results = []
        for task in task_list:
            if isinstance(task,tuple):
                future = self.submit(func, *task)
            else:
                future = self.submit(func, task)
            results.append(future)
        for future in as_completed(results):
            args, kwargs, result = self.get_result(future)
            if isinstance(result, Exception):
                print(f"Task failed with exception: result={result}\n")
                print(f"Args: {args}, kwargs: {kwargs}")
                # raise Exception
            # else:
            #     print(result)
        self.shutdown()




